package com.yrk.controller;

import com.yrk.entity.User;
import com.yrk.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserServiceImpl userServiceImpl;
    //登录
    @RequestMapping("/login")
    public String login(String username, String password, RedirectAttributes redirectAttributes) {
        if (username==null || password==null) {
            return "login";
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        User user1=userServiceImpl.loginUser(user);
        if (user.getPassword().equals(user1.getPassword())) {
            redirectAttributes.addFlashAttribute("user", user);
            return "redirect:/getUserList";
        }else{
            return "login";
        }
    }
    //注册
    @RequestMapping("/regist")
    public String regist(User user) {
        int num=0;
        if (user.getUsername()==null||user.getPassword()==null||user.getSex()==null||user.getTel()==null){
            return "regist";
        }else {
            num=userServiceImpl.registerUser(user);
        }
        if (num>0) {
            return "login";
        } else{
            return "regist";
        }
    }
    //增加
    @RequestMapping("/addUser")
    public int addUser(@RequestBody User user) {
        return userServiceImpl.addUser(user);
    }
    //删除
    @RequestMapping("/daleteUser")
    public String deleteUser(int user_id) {
        User user = new User();
        user.setUser_id(user_id);
        int num=userServiceImpl.deleteUser(user);
        return "redirect:/getUserList";
    }
    //查询全部
    @RequestMapping("/getUserList")
    public String getUserList(Model model) {
        List<User> list =userServiceImpl.getUserList();
        model.addAttribute("list", list);
        return "user";
    }
}
